package io;

import java.io.*;
import java.util.Scanner;

public class IODemo15 {
    public static void main(String[] args) throws IOException {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要搜索的路径");
        String rootPath = scanner.next();
        System.out.println("请输入要查询的词");
        String word = scanner.next();
        File rootFile = new File(rootPath);
        if(!rootFile.isDirectory()) {
            System.out.println("输入的搜索路径有误");
            return;
        }
        scanDir2(rootFile,word);
    }

    private static void scanDir2(File rootFile, String word) throws IOException {
        File[] files = rootFile.listFiles();
        if(files == null){
            return;
        }
        for (File file : files){
            System.out.println("当前搜索到："+file.getAbsolutePath());
            if(file.isFile()){//如果是文件
                //根据内容进行搜索
                searchInFile(file,word);

            } else if (file.isDirectory()) {
                //是目录就遍历
                scanDir2(rootFile,word);
            }else {
                //暂时不需要
                ;
            }
        }
    }

    private static void searchInFile(File file, String word) throws IOException {
        //通过这个方法在文件内部进行搜索
        //1、把文件内容读取出来
        StringBuilder stringBuilder = new StringBuilder();
        try(InputStream inputStream = new FileInputStream(file)){
            while(true){
                byte[] buffer = new byte[1024];
                int n = inputStream.read(buffer);
                if(n == -1){
                    break;
                }
                //此处只是读取出文件的一部分需要把整体内容拼接在一起
                String s = new String(buffer,0,n);
                stringBuilder.append(s);
            }//当循环结束后StringBuilder就拿到整体的内容了
            if (stringBuilder.indexOf(word) == -1){
                //不存在
                return;
            }
            System.out.println("找到了，包含"+word+"的文件存在于"+file.getAbsolutePath());
        }
    }
}
